﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Luna;
using VulnDBExplorer.Services;
using Luna.Framework.Manifest;
using Luna.Framework;
using VulnDB.Action.DataCollectors.Services.CodeAge;
using System.IO;
using TextDataExtractor.DEML;
using VulnDBExplorer.Framework.Impl;
using VulnDBExplorer.Services.Impl;

namespace VulnDB.Action.DataCollectors.Actions {
	
	public class ProfileCodeAgeAction: DataCollectorAction {

		public ProfileCodeAgeAction() {
			this.ExecutionMode = ActionExecutionMode.SeparatedThread;
		}

		public ISourceProfileStorage Storage;

		protected override void onExecute(object sender, Luna.Framework.ActionExecutionArgs arg) {
			if (arg.Data is IConfigurationManifest) {
				IConfigurationManifest m = (arg.Data as IConfigurationManifest);
				ICodebase cb = (ICodebase)Framework.resolveObject(arg.Context,
						new Uri(m.getProperty("codebase", "")), arg.Data);
				string annotationFile = m.getProperty("annotatedFile", "");
				string patternFile = m.getProperty("deml", "");

				//if (Storage == null)
					//Storage = new SourceProfileStorage("codeprofile.dat", "codeprofile.idx");
				Storage = new SqlSourceProfileStorage(cb, "ranarog", "CodeProfile");

				if (annotationFile.fileExists() && cb != null) {
					if (cb is HgCodebase) {
						IProgressMonitor mon = Application.createProgressMonitor();
						CodeProfile cp = new CodeProfile(cb, Storage);
						cp.processHgAnnotatedFile(new StreamReader(annotationFile), mon);
					}
					else if (patternFile.fileExists()) {
						DemlRegistry r = new DemlRegistry();
						r.loadPatterns(patternFile);

						AbstractPattern pat = r.Patterns.FirstOrDefault(p => p.getArgument("for").Equals("annotated-file"));
						if (pat != null) {
							IProgressMonitor mon = Application.createProgressMonitor();
							CodeProfile cp = new CodeProfile(cb, Storage);
							cp.processAnnotatedFile(new StreamReader(annotationFile), pat, mon);
						}
					}
				}
			}
		}
	}
}
